package com.topscomm.mis.cbb.file.compare.word;

import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.xmlbeans.XmlOptions;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTComments;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CommentsDocument;

import javax.xml.namespace.QName;
import java.io.IOException;
import java.io.OutputStream;

import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;

/**
 * @description: POI中Word的批注对象
 * @author: zhanglongfei
 * @date: 2023/2/20 17:56
 */
public class XWPFWordCommentsDocument extends POIXMLDocumentPart {

    private CTComments comments;

    public XWPFWordCommentsDocument(PackagePart part) {
        super(part);
        try {
            comments = CommentsDocument.Factory.parse(part.getInputStream(), DEFAULT_XML_OPTIONS).getComments();
        } catch (Exception ex) {
            // there was no comments yet
        }
        if (comments == null) comments = CommentsDocument.Factory.newInstance().addNewComments();
    }

    public CTComments getComments() {
        return comments;
    }

    @Override
    protected void commit() throws IOException {
        XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
        xmlOptions.setSaveSyntheticDocumentElement(new QName(CTComments.type.getName().getNamespaceURI(), "comments"));
        PackagePart part = getPackagePart();
        OutputStream out = part.getOutputStream();
        comments.save(out, xmlOptions);
        out.close();
    }

}
